package org.wwx.register.core;

import org.wwx.register.health.HealthChecker;
import org.wwx.register.model.ServiceInstance;
import org.wwx.register.server.RegistryServer;
import org.wwx.register.server.impl.BuiltInHttpServer;
import storage.ServiceStorage;
import storage.impl.RedisStorage;

import java.util.List;

/**
 * 轻量级可扩展注册中心核心类，提供注册中心构建器模式配置
 * <p>主要功能包括：
 * <ul>
 *   <li>内置HTTP服务端实现服务注册/发现接口</li>
 *   <li>支持多种嵌入式Web服务器（内置/Jetty/Tomcat）</li>
 *   <li>可配置健康检查机制</li>
 *   <li>提供存储组件扩展能力</li>
 * </ul>
 *
 * @date 2025/6/6
 * @author王闻薪
 */
public class LightweightRegistry {
    private final ServiceStorage storage;
    private final RegistryServer server;
    private final HealthChecker healthChecker;

    public LightweightRegistry(ServiceStorage storage, RegistryServer server, HealthChecker healthChecker) {
        this.storage = storage;
        this.server = server;
        this.healthChecker = healthChecker;
    }

    public void start() throws Exception {
        server.start();
        if (healthChecker != null) {
            healthChecker.start();
        }
    }

    public void stop() throws Exception {
        if (healthChecker != null) {
            healthChecker.stop();
        }
        server.stop();
    }

    /**
     * 注册服务实例
     *
     * @param serviceName 服务名称（建议使用全限定类名）
     * @param instance    服务实例信息
     */
    public void registerService(String serviceName, ServiceInstance instance) {
        storage.registerService(serviceName, instance);
    }

    /**
     * 发现可用服务实例
     *
     * @param serviceName 服务名称
     * @return 可用实例列表（按最近心跳时间排序）
     */
    public List<ServiceInstance> discoverService(String serviceName) {
        return storage.getServiceInstances(serviceName);
    }

    public static class Builder {
//                private ServiceStorage storage = new InMemoryStorage();
        private ServiceStorage storage = new RedisStorage();
        private RegistryServer server;
        private HealthChecker healthChecker;
        private int httpPort = 8080;

        /**
         * 配置自定义存储实现
         *
         * @param storage 存储组件实例（需实现ServiceStorage接口）
         * @return Builder实例保持链式调用
         */
        public Builder withStorage(ServiceStorage storage) {
            this.storage = storage;
            return this;
        }

        /**
         * 启用内置HTTP服务器
         *
         * @param port HTTP服务监听端口
         * @return Builder实例保持链式调用
         */
        public Builder withBuiltInHttpServer(int port) {
            this.httpPort = port;
            return this;
        }

        /**
         * 启用Tomcat嵌入式服务器
         * （需要实现TomcatRegistryServer类）
         *
         * @return Builder实例保持链式调用
         */
        public Builder withTomcatServer() {
            // 实际实现中会返回Tomcat实现
            // this.server = new TomcatRegistryServer(storage);
            return this;
        }

        /**
         * 启用Jetty嵌入式服务器
         * （需要实现JettyRegistryServer类）
         *
         * @return Builder实例保持链式调用
         */
        public Builder withJettyServer() {
            // 实际实现中会返回Jetty实现
            // this.server = new JettyRegistryServer(storage);
            return this;
        }

        /**
         * 启用健康检查机制
         *
         * @param expirationSeconds 实例过期时间（单位：秒）
         * @return Builder实例保持链式调用
         */
        public Builder withHealthCheck(long expirationSeconds) {
            this.healthChecker = new HealthChecker(storage, expirationSeconds * 1000);
            return this;
        }

        /**
         * 构建注册中心实例
         * <p>当未显式配置服务器时，默认使用内置HTTP服务器</p>
         *
         * @return 配置完成的轻量级注册中心实例
         */
        public LightweightRegistry build() {
            if (server == null) {
                server = new BuiltInHttpServer(storage, httpPort);
            }
            return new LightweightRegistry(storage, server, healthChecker);
        }

    }
}